import {EyeOutlined, PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumnType} from '@ant-design/pro-components';
import {
  BetaSchemaForm,
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import {Button, message, Image, Form, Popconfirm, Modal, Space, Tooltip} from 'antd';
import React, {useRef, useState} from 'react';
import type {TableListItem, TableListPagination} from './data';
import {addArticle, getArticlePage, batchDelArticle, updateArticle} from './service';
import './index.less'
import CustomImgUpload from '@/components/CustomImgUpload';
import CustomEditor from '@/components/CustomRichEditor';
import CustomFileUpload from '@/components/CustomFileUpload';

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);

  const [editForm] = Form.useForm()
  const [addForm] = Form.useForm()

  const columns: ProColumnType<any>[] = [
    {
      title: '序号',
      dataIndex: '#',
      key: '#',
      width: 80,
      hideInSearch: true,
      hideInForm: true,
      fixed: 'left',
      render(dom, entity, index) {
        return index + 1;
      },
      editable: false,
    },
    {
      title: '文章标题',
      dataIndex: 'title',
      fieldProps: {
        placeholder: '请输入文章标题'
      },
      ellipsis: true,
      render(text: any, record: any) {
        return <div style={{width: 200,overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'}}>{record?.title}</div>
      }
      // width: '20%',
    },
    {
      title: '文章类型',
      dataIndex: 'type',
      key: 'type',
      valueType: 'select',
      valueEnum: {
        News: {
          text: '新闻中心'
        },
      },
      hideInForm: true,
    },
    {
      title: '文章类型',
      dataIndex: 'type',
      key: 'type',
      fieldProps: {disabled: true},
      valueType: 'select',
      valueEnum: {
        News: {
          text: '新闻中心'
        },
      },
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '封面图片',
      dataIndex: 'imgUrl',
      valueType: 'image',
      hideInSearch: true,
      renderFormItem: () => {
        return <CustomImgUpload style={{width: 350}}/>
      },
      render: (text: any, record: any) => {
        return record?.imgUrl ? <Image width={50} preview={{
          mask: <EyeOutlined/>
        }} src={record?.imgUrl}/> : '-'
      },
      formItemProps: () => {
        return {
          rules: [{required: true, message: '此项为必填项'}],
        };
      },
      key: 'imgUrl',
      // width: '20%',
    },
    {
      title: '文章概述',
      dataIndex: 'summary',
      ellipsis: true,
      hideInSearch: true,
      fieldProps: {
        placeholder: '请输入文章概述'
      },
      key: 'summary',
      valueType: 'textarea',
      // width: '20%',
    },

    {
      title: '文章内容',
      dataIndex: 'content',
      key: 'content',
      hideInSearch: true,
      valueType: 'textarea',
      tooltip: '支持MarkDown语法',
      ellipsis: true,
      renderFormItem() {
        return <CustomEditor/>
      },
      render: (text: any, record: any) => {
        return record.content ?
          <Tooltip
            placement="topLeft"
            title={<div style={{maxHeight: 300, overflowY: 'auto'}}>{record.content}</div>}>
            <div style={{width: 250,overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'}}>{record.content}</div>
          </Tooltip> : '-'
      },
    },

    {
      title: '附件',
      dataIndex: 'fileUrl',
      key: 'fileUrl',
      hideInSearch: true,
      renderFormItem: () => {
        return <CustomFileUpload style={{width: 350}}/>
      },
      render: (text: any, record: any) => {
        try {
          const fileUrls = JSON.parse(record?.fileUrl)
          return fileUrls ? <Space wrap>
            {fileUrls?.map?.((it: any, index: number) => {
              return <div key={it?.url + index}>
                <a href={it?.url}>{it?.name}</a>
              </div>
            })}
          </Space> : '-'
        } catch (e) {
        }
        return '-'
      },

    },

    {
      title: '相关链接',
      dataIndex: 'linkUrl',
      key: 'linkUrl',
      hideInSearch: true,
      valueType: 'text',
    },

    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      key: 'gmtCreate',
      hideInSearch: true,
      valueType: 'dateTime',
      hideInForm: true,
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified',
      key: 'gmtModified',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      key: 'action',
      valueType: 'option',
      width: 120,
      fixed: 'right',
      render: (_, record: any) => {
        return [
          <BetaSchemaForm<any>
            key="eidit"
            form={editForm}
            trigger={<a
              onClick={() => {
                console.log('record', record);

                editForm.setFieldsValue({
                  ...record,
                  imgUrl: {
                    url: record?.imgUrl
                  },
                  fileUrl: record?.fileUrl ? JSON.parse(record?.fileUrl) : undefined
                })
              }}
            >
              编辑
            </a>}
            layoutType={'ModalForm'}
            modalProps={{
              width: 1000,
              title: '编辑文章'
            }}
            // rowProps={{
            //   gutter: [16, 16],
            // }}
            // colProps={{
            //   span: 12,
            // }}
            // grid={false}
            onFinish={async (values) => {
              console.log('values', values);
              const hide = message.loading('正在保存');
              try {
                const res = await updateArticle({
                  ...values,
                  id: record?.id,
                  imgUrl: values?.imgUrl?.url,
                  fileUrl: JSON.stringify(values?.fileUrl),
                  isShow: values?.isShow ? 1 : 0
                })
                hide();
                if (res?.code === 0) {
                  message.success('保存成功，即将刷新');
                  actionRef.current?.reload()
                  return true;
                } else {
                  message.error('保存失败，请重试');
                  return false;
                }
              } catch (error) {
                hide();
                message.error('保存失败，请重试');
                return false;
              }
            }}
            columns={columns as any}
          />,
          <Popconfirm
            key="del"
            title="删除文章"
            description={<>
              <p>确认删除 <b>{record?.name}</b> 文章?</p>
            </>}
            onConfirm={async () => {
              const hide = message.loading('正在删除');

              try {
                const res = await batchDelArticle({
                  idList: [record?.id]
                })
                hide();
                if (res.code === 0) {
                  message.success('删除成功');
                  actionRef.current?.reload()
                  return true
                } else {
                  hide();
                  message.error('删除失败请重试！');
                  return false;
                }
              } catch (e) {
                hide();
                message.error('删除失败请重试！');
                return false;
              }
            }}
            okText="是"
            cancelText="否"
          >
            <a>删除</a>
          </Popconfirm>
          ,
        ];
      },
    },
  ];

  return (
    <PageContainer className='article_wrap'>
      <ProTable<TableListItem, TableListPagination>
        headerTitle="文章管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        scroll={{x: 'max-content'}}
        toolBarRender={() => [
          <BetaSchemaForm<any>
            key={'add'}
            trigger={<Button
              type="primary"
              key="primary"
              onClick={() => {
                addForm.resetFields()

                addForm.setFieldValue('type', "News")
              }}
            >
              <PlusOutlined/> 新建
            </Button>}
            // layoutType={'DrawerForm'}
            layoutType='ModalForm'
            form={addForm}
            // drawerProps={{
            //   width: 500,
            //   title: '新增文章'
            // }}
            modalProps={{
              width: 1000,
              title: '新增文章'
            }}
            // rowProps={{
            //   gutter: [16, 16],
            // }}
            // colProps={{
            //   span: 12,
            // }}
            // grid={false}
            onFinish={async (values) => {
              console.log('values', values);

              const hide = message.loading('正在保存');

              try {
                const res = await addArticle({
                  ...values,
                  imgUrl: values?.imgUrl?.url,
                  fileUrl: JSON.stringify(values?.fileUrl),
                  isShow: values?.isShow ? 1 : 0
                })
                hide();
                if (res?.code === 0) {
                  message.success('保存成功，即将刷新');
                  actionRef.current?.reload()
                  return true;
                } else {
                  message.error('保存失败，请重试');
                  return false;
                }
              } catch (error) {
                hide();
                message.error('保存失败，请重试');
                return false;
              }
            }}
            columns={columns as any}
          />
          ,
        ]}
        request={async ({current, pageSize, ...other}) => {
          // @ts-ignore
          const res = await getArticlePage({
            page: current,
            size: pageSize,
            ...other
          })

          return {
            total: res?.data?.total_records,
            data: res?.data?.current_data
          }
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState?.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              Modal.confirm({
                title: `确认删除 ${selectedRowsState?.length} 条数据?`,
                content: `请谨慎操作，删除后不可恢复`,
                async onOk() {
                  const hide = message.loading('正在删除');

                  try {
                    const res = await batchDelArticle({
                      idList: selectedRowsState?.map((item: any) => item.id)
                    })
                    hide();
                    if (res.code === 0) {
                      message.success('删除成功');
                      setSelectedRows([]);
                      actionRef.current?.reload()
                      return true
                    } else {
                      hide();
                      message.error('删除失败请重试！');
                      return false;
                    }
                  } catch (e) {
                    hide();
                    message.error('删除失败请重试！');
                    return false;
                  }

                }
              })
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
    </PageContainer>
  );
};

export default TableList;
